/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cassys.action;

import cassys.dataaccess.DAOException;
import cassys.datatransferobjects.LecturerDTO;
import cassys.datatransferobjects.ModuleDTO;
import cassys.datatransferobjects.StudentModuleTeamDTO;
import cassys.datatransferobjects.UserDTO;
import cassys.delegates.LecturerDelegate;
import cassys.delegates.ModuleDelegate;
import cassys.delegates.StudentModuleTeamDelegate;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.rmi.RemoteException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author User
 */
public class ModuleAction extends CassysSupport {

    private File usersfile;
    private ModuleDTO module;
    private String moduleCode;
    private boolean isUpdate = false;
    private List<String> lecturers;
    private ArrayList<LecturerDTO> allLecturers;
    //private Set<LecturerDTO> lecturerTeaching;
    //private ArrayList<LecturerDTO> lecturers = new ArrayList<LecturerDTO>();
    private ModuleDelegate mDelegate = new ModuleDelegate();
    private LecturerDelegate lectDelegate = new LecturerDelegate();

    public List<String> getLecturerNames() throws Exception {
        allLecturers = lectDelegate.findAllLecturers();
        List<String> names = new ArrayList<String>();
        if (allLecturers != null && allLecturers.size() > 0) {
            Iterator<LecturerDTO> iter = allLecturers.iterator();
            while (iter.hasNext()) {
                names.add(iter.next().getUsername());
            }
        }
        return names;
    }

    @Override
    public String execute() throws Exception {
        //isUpdate = false;
        return list();
    }

    public List<ModuleDTO> getModules() throws Exception {
        //logger.info("getModules");
        //System.out.println("Count" +mDelegate.findAllModules().get(0).getLecturerTeaching().size());
        return mDelegate.findAllModules();
    }

    public String list() {
        //logger.info("list");
        return "modulelist";
    }

    public String view() {
        if (usersfile != null) {
            importStudents();
        }

        module = findModuleByCode(moduleCode);

        UserDTO user = (UserDTO) session.get("user");
        if (user.getRole().equals("student"))
            return "moduleviewstudent";
        
        return "moduleview";
    }

    public String create() throws Exception {
        isUpdate = false;
        System.out.println("Add " + isUpdate);
        return "moduleform";
    }

    public String delete() throws Exception {
        //logger.debug("delete");
        module = findModuleByCode(moduleCode);
        module.setLecturerTeaching(null);
        mDelegate.deleteModule(module);
        return "modulelist";
    }

    public String add() throws Exception {
        System.out.println("Lect" + lecturers);
        return "moduleform";
    }

    public String edit() throws Exception {
        //LOG.info("\nedit(" + productId + ")");
        System.out.println("Edit " + isUpdate);
        module = findModuleByCode(moduleCode);
        System.out.println("Module Code" + module.getModuleCode());
        System.out.println("Title " + module.getTitle());
        System.out.println("Description " + module.getDescription());
        System.out.println("Type " + module.getType());
        System.out.println("Mark " + module.getMaximumMarks());
        System.out.println("Weight " + module.getWeight());
        System.out.println("Range " + module.getFromRange() + "-" + module.getToRange());
        System.out.println("Owner " + module.getOwner());
        if (module != null) {
            isUpdate = true;
            System.out.println("Edit " + isUpdate);

            if (module.getLecturerTeaching() != null && module.getLecturerTeaching().size() > 0) {
                List<String> ids = new ArrayList<String>();
                Iterator<LecturerDTO> iter = module.getLecturerTeaching().iterator();
                while (iter.hasNext()) {
                    ids.add(iter.next().getLecturername());
                }
                setLecturers(ids);
            }
        }
        return "moduleform";
    }

    public String update() throws Exception {

        System.out.println("Module Code" + module.getModuleCode());
        System.out.println("Title " + module.getTitle());
        System.out.println("Description " + module.getDescription());
        System.out.println("Type " + module.getType());
        System.out.println("Mark " + module.getMaximumMarks());
        System.out.println("Weight " + module.getWeight());
        System.out.println("Range " + module.getFromRange() + "-" + module.getToRange());
        System.out.println("Owner " + module.getOwner());
        System.out.println("lecturers" + lecturers);

        //List<LecturerDTO> lecturerTeaching = new ArrayList<LecturerDTO>();
        if (lecturers != null && lecturers.size() > 0) {
            Set<LecturerDTO> lecturerTeaching = new TreeSet<LecturerDTO>();
            Iterator<String> iter = lecturers.iterator();
            while (iter.hasNext()) {
                LecturerDTO temp = lectDelegate.findLecturerByName(iter.next());
                lecturerTeaching.add(temp);
            }
            module.setLecturerTeaching(lecturerTeaching);
        }

        /*
         * if(lecturers.size() > 0){ Set<LecturerDTO> lecturerTeaching = new
         * TreeSet<LecturerDTO>(); Iterator<String> iter = lecturers.iterator();
         * while(iter.hasNext()){ System.out.println(iter.next()); //
         * LecturerDTO lect = findLecturerByName(iter.next()); //if(lect !=
         * null) // System.out.println(lect.getUserId());
         * //lecturerTeaching.add(lect); }
         * //module.setLecturerTeaching(lecturerTeaching); }
         */

        if (isUpdate) {
            mDelegate.updateModule(module);
        } else {
            mDelegate.insertModule(module);
        }


        return list();
    }

    /*
     * public LecturerDTO findLecturerByName(String lecturerName) { LecturerDTO
     * lect = null;
     *
     * ArrayList<LecturerDTO> tempLects = new ArrayList<LecturerDTO>();
     * LecturerDTO temp = new LecturerDTO("swarna", "swarna", "L-001", "swarna",
     * "lecturer", "swarna@mail.com"); tempLects.add(temp);
     *
     * LecturerDTO temp2 = new LecturerDTO("boonkui", "boonkui", "L-002",
     * "boonkui", "lecturer", "boonkui@mail.com"); tempLects.add(temp2);
     * Iterator<LecturerDTO> iter = tempLects.iterator(); while (iter.hasNext())
     * { if (iter.next().getLecturername().equalsIgnoreCase(lecturerName)) {
     * lect = iter.next(); } } return lect; }
     */
    public ModuleDTO findModuleByCode(String code) {
        ModuleDTO mod = null;
        try {
            mod = mDelegate.findModule(code);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return mod;
    }

    public ModuleDTO getModule() {
        return module;
    }

    public void setModule(ModuleDTO module) {
        this.module = module;
    }

    public boolean isIsUpdate() {
        return isUpdate;
    }

    public void setIsUpdate(boolean isUpdate) {
        this.isUpdate = isUpdate;
    }

    public String getModuleCode() {
        return moduleCode;
    }

    public void setModuleCode(String moduleCode) {
        this.moduleCode = moduleCode;
    }

    public List<String> getLecturers() {
        return lecturers;
    }

    public void setLecturers(List<String> lecturers) {
        this.lecturers = lecturers;
    }

    @Override
    public void validate() {
        System.out.println(isUpdate);
        System.out.println("validate");
        if (module != null) {
            if (module.getModuleCode().trim().length() == 0) {
                addFieldError("module.moduleCode", "Module Code is required");
            }
            if (module.getTitle().trim().length() == 0) {
                addFieldError("module.title", "Module Title is required");
            }
            if (module.getMaximumMarks() <= 0) {
                addFieldError("module.maximumMarks", "Maximum Mark is required");
            }
            if (module.getWeight() <= 0) {
                addFieldError("module.weight", "Weight is required");
            }
        }
    }

    public File getUsersfile() {
        return usersfile;
    }

    public void setUsersfile(File file) {
        this.usersfile = file;
    }

    protected int getRandomNumber() {
        Random randomGenerator = new Random();
        return randomGenerator.nextInt();
    }

    public void importStudents() {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(usersfile));
            StudentModuleTeamDelegate stdModTeamDelegate = new StudentModuleTeamDelegate();
            String line;
            while ((line = reader.readLine()) != null) {
                try {
                    StudentModuleTeamDTO tempDTO = new StudentModuleTeamDTO();
                    tempDTO.setStudentModuleId("M-" + getRandomNumber());
                    tempDTO.setModulecode(moduleCode);
                    tempDTO.setStudentId(line);
                    stdModTeamDelegate.insertStudentModuleTeam(tempDTO);
                } catch (Exception e) {
                }

            }
        } catch (Exception e) {
        }
    }
}
